<template>
    <v-container>
        <div class="detail_header">
            <!-- <span>{{ word.userId }}</span><br><span>{{$store.state.userInfo.userId}}</span><br><span>{{word.flag}}</span><br> -->
            <span v-if="word.userId === $store.state.userInfo.userId && word.flag === 'USER'" @click="editWord"
                style="float:right"><v-icon color="primary" icon="mdi-square-edit-outline"></v-icon></span>
            <span @click="copyWord" style="float:right"><v-icon color="primary" icon="mdi-plus"></v-icon></span>
            <strong>{{ word.word }}</strong>
            <v-img v-if="word.image != null" :width="100" aspect-ratio="1/1" cover :src="word.image"></v-img>
            <br>
            <PronunciationComponent direction="horizon" ref="pronunciationComponent" balance="left" />
        </div>
        <div v-if="word.etymologyPlain != null">
            <v-divider></v-divider>
            <small>单词词源</small>
            <p>{{ word.etymologyPlain }}</p>
            <br>
        </div>
        <div v-if="word.wordExchange != null">
            <v-divider></v-divider>
            <small>单词变形</small>
            <p :key="index" v-for="(exchange, index) in Object.keys(word.wordExchange)">
                {{ exchange }}：{{ word.wordExchange[exchange] }}
            </p>
            <br>
        </div>
        <div v-if="word.remember != null">
            <!-- <v-divider></v-divider> -->
            <small>记忆技巧：</small>
            <span>{{ word.remember }}</span>
            <br>
        </div>
        <div v-if="word.tag != null && word.tag.length > 0">
            <small class="word_tag" :key="index" v-for="(mean, index) in word.tag">{{ mean }}</small>
            <br>
        </div>
        <div v-if="word.translatedMeanings != null && word.translatedMeanings.length > 0">
            <v-divider></v-divider>
            <small>单词释义</small>
            <p :key="index" v-for="(mean, index) in word.translatedMeanings">{{ mean.type }}.{{ mean.meaning }}</p>
            <br>
        </div>
        <div>
            <v-divider></v-divider>
            <small>原释义</small>
            <div v-for="(mean, index) in word.originalMeanings" :key="index">
                <strong v-if="mean.type != null">{{ mean.type }} </strong>
                <strong v-if="mean.symbol != null">[{{ mean.symbol }}]</strong>
                <p :style="{ textIndent: mean.type != null && mean.symbol != null ? '10px' : '0' }"
                    v-for="(item, index2) in mean.meaning" :key="index2">
                    {{ index2 + 1 }}.
                    {{ item.explain }}
                </p>
            </div>

            <br>
        </div>
        <div>
            <v-divider></v-divider>
            <small>相关例句</small>
            <p :key="index" v-for="(sentence, index) in word.sentence" style="margin-bottom: 10px;">
                {{ sentence.self }}
                <br>
                {{ sentence.mean }}
            </p>
        </div>
        <span style="display: block;width: fit-content;margin: auto;color:grey;cursor: pointer;">数据来源：
            <strong style="color:rgb(var(--v-theme-primary))" @click="toggle(word.sourceUrl)">{{ word.source }}</strong>
            <v-icon v-hasPermi="['read-word-refresh-admin']" v-if="this.word.sourceUrl != null" @click="refreshWord" icon="mdi-refresh" />
        </span>
        <div style="width: 100%;height: 10px;margin-bottom: 60px;"></div>
        <div v-if="showCandidate" class="detail_bottom">
            <div v-if="candidate.previous == null && candidate.curPage == 1" style="width: 50px;height: 20px;color: white;">占位
            </div>
            <div @click="setPage(candidate.curPage - 1)" v-if="candidate.previous == null && candidate.curPage > 1">
                <v-icon start icon="mdi-arrow-left"></v-icon>上一页
            </div>
            <div @click="nextWord(candidate.previous, 'pre')" v-if="candidate.previous != null">
                <v-icon start icon="mdi-arrow-left"></v-icon>{{ candidate.previous.word }}
            </div>
            <div @click="nextWord(candidate.next, 'next')" v-if="candidate.next != null">
                {{ candidate.next.word }}<v-icon start icon="mdi-arrow-right"></v-icon>
            </div>
            <div @click="setPage(candidate.curPage + 1)" v-if="candidate.next == null && candidate.hasNextPage">
                下一页<v-icon start icon="mdi-arrow-right"></v-icon>
            </div>
        </div>
        <v-overlay :model-value="overlay" class="align-center justify-center">
            <v-progress-circular color="primary" indeterminate size="64"></v-progress-circular>
        </v-overlay>
    </v-container>
    <i-frame-component ref="iframe" />
</template>

<script>
import { isResourceExist } from "@/api/voice";
import { getWordDetail, getDefaultWordDetail, refreshWord } from "@/api/word.js";
import IFrameComponent from '@/components/IFrameComponent.vue';
// import { getCandidate } from "@/api/wordLine.js";

export default {
    components: { IFrameComponent },
    name: 'WordView',
    props: {
        showCandidate: {
            type: Boolean,
            default: true
        },
        initiative: {
            type: String, default: 'active'
        },
        nextCallback: Function,
        setPageListener: Function
    },
    data() {
        return {
            word: {},
            audio: null,
            isPlaying: false,
            audioUrl: null,
            overlay: false,
            candidate: {
                previous: null,
                next: null,
            },
            curIndex: 0,
            pronunciationStatusList: [{}, {}]
        }
    },
    created() {
        this.curIndex = this.$route.params.curIndex
        if (this.initiative === 'active') {
            this.detail({
                wordId: this.$route.params.wordId,
                bookId: this.$route.params.bookId,
                flag: this.$route.params.default,
                curIndex: this.curIndex,
            })
        }
    },
    unmounted() {
        if (this.audio != null) {
            this.audio.pause()
            this.audio = null
        }
    },
    methods: {
        detail(row) {
            this.overlay = true
            if (this.audio != null) this.audio.pause()
            if (this.$route.params.default == true || this.$route.params.default == 'true' || row.default == true) {
                getDefaultWordDetail(row).then(resp => {
                    // console.log(resp.data);
                    if (resp.data != null) {
                        this.word = resp.data
                        this.$refs.pronunciationComponent.setResource(this.word.pronunciation)
                    } else
                        this.word = { word: '系统错误❌' }
                }).finally(() => this.overlay = false)
            } else {
                getWordDetail(row).then(resp => {
                    if (resp.data != null) {
                        this.word = resp.data
                        this.$refs.pronunciationComponent.setResource(this.word.pronunciation)
                    } else
                        this.word = { word: '系统错误❌' }
                }).finally(() => this.overlay = false)
            }
        },
        setWordDetail(wordData) {
            if (this.audio != null) {
                this.audio.pause()
                this.audio = null
            }
            this.word = wordData
            this.$refs.pronunciationComponent.setResource(this.word.pronunciation)
        },
        editWord() {
            this.$router.push({ name: 'diy_word', params: { wordId: this.word.wordId, bookId: this.$route.params.bookId, copy: false } })
        },
        copyWord() {
            this.$router.push({ name: 'diy_word', params: { wordId: this.word.wordId, bookId: this.$route.params.bookId, copy: true } })
        },
        playAudio(pronunciation, index) {
            if (this.pronunciationStatusList[index] == null || this.pronunciationStatusList[index].status != 200) return
            if (this.audio != null && pronunciation.resource == this.audioUrl) {
                this.audio.pause()
                this.pronunciationStatusList[index].color = 'black'
                this.audio = null
                return
            } else if (pronunciation.resource != this.audioUrl) {
                if (this.audio != null) this.audio.pause()
                this.pronunciationStatusList.forEach(item => item.color = 'black')
                this.audio = new Audio(pronunciation.resource)
                this.audio.loop = true
                this.audio.play()
                this.pronunciationStatusList[index].color = 'green'
                this.audioUrl = pronunciation.resource
                return
            }
            this.audio = new Audio(pronunciation.resource)
            this.audio.loop = true
            this.audio.play()
            this.pronunciationStatusList[index].color = 'green'
            this.audioUrl = pronunciation.resource
        },
        nextWord(word, direction) {
            if (this.audio != null) {
                this.audio.pause()
                this.audio = null
            }
            this.setWordDetail(word)
            if (this.nextCallback) this.nextCallback(direction)
        },
        setCandidate(pre, next, curPage, hasNextPage) {
            this.candidate.previous = pre
            this.candidate.next = next
            this.candidate.hasNextPage = hasNextPage
            this.candidate.curPage = curPage
        },
        setPage(pageNum) {
            if (this.setPageListener == null) return
            if (this.audio != null) {
                this.audio.pause()
                this.audio = null
            }
            this.setPageListener(pageNum)
        },
        refreshWord() {
            if (this.word.sourceUrl == null) return
            this.overlay = true
            refreshWord(this.word.wordId).then(resp => {
                if (resp.data == null) return
                this.word = resp.data
            }).finally(() => this.overlay = false)
        },
        toggle(url) {
            if (url != null) this.$refs.iframe.toggle(true, url)
        },
        applyDestroyed() {
            if (this.audio != null) {
                this.audio.pause()
                this.audio = null
                return
            }
            this.$refs.pronunciationComponent.stop()
        },
        isSymbolRescourceExist() {
            let word = this.word
            if (word.pronunciation == null || word.pronunciation.length < 0) return
            let pronunciationList = word.pronunciation
            for (let i = 0; i < pronunciationList.length; i++) {
                if (pronunciationList[i].resource == null || pronunciationList[i].resource == '') continue
                isResourceExist(pronunciationList[i].resource).then(resp => {
                    this.pronunciationStatusList[i] = { status: resp.status }
                    this.pronunciationStatusList[i].color = resp.status == 200 ? 'black' : 'grey'
                })
            }
        }
    }
}
</script>

<style scoped>
.detail_header strong {
    font-size: 50px;
}

.detail_bottom {
    display: flex;
    margin: auto;
    justify-content: space-between;
    position: fixed;
    bottom: 0px;
    padding-bottom: 10px;
    background-color: white;
    width: 48%;
    padding-top: 5px;
    border-top: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
}

.detail_bottom div {
    font-size: 18px;
    cursor: pointer;
}

.word_tag {
    background: #f2f2f2;
    border-radius: 2px;
    box-sizing: border-box;
    color: #999;
    font-size: 14px;
    height: 20px;
    line-height: 20px;
    margin-right: 12px;
    padding: 0 6px;
}

@media screen and (max-width: 1300px) {
    .detail_bottom {
        width: 45%;
    }
}

@media screen and (max-width: 768px) {
    .detail_bottom {
        width: 90%;
    }
}
</style>